import { makeAutoObservable, observable } from 'mobx';
import * as api from './api';
import { t } from '@lingui/macro';
import { Message } from '@alifd/next';

export default class RuleStore {
  _args = {
    search: {
    },
    pg: {
      page: 0,
      sort: ['crDate;DESC'],
      size: 10,
    },
  };
  total = 0;
  data = [];
  loading = false;

  _groups = [];
  _group_id = null;

  _pageData = [];

  _MESSAGE_TEXT = {
    1: t`不能重复设置积分区间，请重新设置！`,
    2: t`结束积分不能小于开始积分，请重新设置！`,
  };

  _isPhone = false;
  _device = false;

  constructor(rootStore) {
    this.rootStore = rootStore;
    makeAutoObservable(this, {
      rootStore: false,
    });
  }

  /**
   * 使用设置的请求参数和分页配置请求列表数据
   * 分页参数为空时保持当前分页配置
   * @param {object} pgInfo 分页参数
   */
  * query(pgInfo) {
    _.mergeWith(this._args.pg, pgInfo, (o, s) => (_.isArray(o) ? s : undefined)); // 数组直接赋值，不合并
    const { search, pg } = toJS(this._args);
    if (!pg.sort?.length) delete pg.sort;
    this.loading = true;
    try {
      this.total = yield api.count({ search });
      this.data = yield api.get({ search, pg });
    } catch (error) {
      Message.error({ content: t`请求失败：${error}` });
      throw error;
    } finally {
      this.loading = false;
    }
  }

  * create(data) {
    yield api.create(data);
    yield this.query();
  }

  * update(data) {
    yield api.update(data);
    yield this.query();
  }

  * updateState(data) {
    yield api.update({ ...data, enable: !data.enable });
    yield this.query();
  }

  * getId(id) {
    const res = yield api.getId(id);
    return observable(res);
  }

  * getDriver(args) {
    return yield api.getDriver(args);
  }

  idx(i) {
    return this._args.pg.page * this._args.pg.size + i + 1;
  }

  get pg() {
    return this._args.pg;
  }

  set pg(pg) {
    this.query({ ...pg });
  }

  get search() {
    this._args.pg.page = 0;
    return this._args.search;
  }

  set search(search) {
    this._args.pg.page = 0;
    this._args.search = search;
    this.query({ page: 0 });
  }

  get tableSort() {
    if (this._args.pg.sort?.length) {
      const [fn, dir] = this._args.pg.sort[0].split(';');
      return { [fn]: dir };
    }
    return undefined;
  }


  /**
   * 校验是否存在交集
   * @param {*} values 输入的指
   * @param {*} state 数据源
   * @returns
   */
  _uniqueBatch(values, show, idx) {
    const { startPoint, endPoint } = values;
    const cloneData = _.cloneDeep(this._pageData);
    // 如果是编辑操作，移除当前索引的数据
    if (show === 'edit') {
      cloneData.splice(idx, 1);
    }
    // 将输入的开始点和结束点转换为数字
    const start = Number(startPoint);
    const end = Number(endPoint);

    // 如果结束点小于开始点，返回错误码 '2'
    if (end < start) {
      return '2';
    }
    // 检查新数据是否与现有数据有重复或交集
    for (let i = 0; i < cloneData.length; i++) {
      const rule = cloneData[i];
      const ruleStart = Number(rule.startPoint);
      const ruleEnd = Number(rule.endPoint);

      // 检查区间是否有重复或交集
      if (
        (start >= ruleStart && start <= ruleEnd) || // 新区间的开始点在现有区间内
        (end >= ruleStart && end <= ruleEnd) || // 新区间的结束点在现有区间内
        (start <= ruleStart && end >= ruleEnd) // 新区间包含现有区间
      ) {
        return '1';
      }
    }
    // 如果所有检查都通过，返回 null 表示没有错误
    return null;
  }
}
